// src/utils/timeUtils.js

/**
 * 格式化时间戳为 "HH:mm" 格式（如：14:30）
 */
export function formatTime(timestamp) {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

/**
 * 格式化时间为 "YYYY-MM-DD HH:mm"
 */
export function formatDateTime(timestamp) {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  const y = date.getFullYear()
  const M = String(date.getMonth() + 1).padStart(2, '0')
  const d = String(date.getDate()).padStart(2, '0')
  const h = String(date.getHours()).padStart(2, '0')
  const m = String(date.getMinutes()).padStart(2, '0')
  return `${y}-${M}-${d} ${h}:${m}`
}

/**
 * 智能格式化时间（推荐用于聊天列表）
 * 支持：刚刚、N分钟前、N小时前、昨天、前天、星期X、M月D日、Y年M月D日
 */
export function formatFriendlyTime(timestamp) {
  if (!timestamp) return ''

  const date = new Date(timestamp)
  const now = new Date()
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
  const yesterday = new Date(today.getTime() - 86400000)
  const beforeYesterday = new Date(yesterday.getTime() - 86400000)
  const oneWeekAgo = new Date(today.getTime() - 7 * 86400000)
  const oneMonthAgo = new Date(today.getFullYear(), today.getMonth() - 1, today.getDate())
  const threeMonthsAgo = new Date(today.getFullYear(), today.getMonth() - 3, today.getDate())
  const oneYearAgo = new Date(today.getFullYear() - 1, today.getMonth(), today.getDate())

  // 时间部分
  const timeStr = date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })

  // 计算时间差（毫秒）
  const diff = now.getTime() - date.getTime()
  const diffSeconds = Math.floor(diff / 1000)
  const diffMinutes = Math.floor(diff / (1000 * 60))
  const diffHours = Math.floor(diff / (1000 * 60 * 60))

  // --- 开始判断 ---
  if (diffSeconds < 10) {
    return '刚刚'
  } else if (diffMinutes < 1) {
    return `${diffSeconds}秒前`
  } else if (diffMinutes < 60) {
    return `${diffMinutes}分钟前`
  } else if (diffHours < 24 && date >= today) {
    return `${diffHours}小时前`
  } else if (date >= yesterday && date < today) {
    return '昨天 ' + timeStr
  } else if (date >= beforeYesterday && date < yesterday) {
    return '前天 ' + timeStr
  } else if (date >= oneWeekAgo) {
    const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
    return weekdays[date.getDay()] + ' ' + timeStr
  } else if (date >= oneMonthAgo) {
    return `${date.getMonth() + 1}月${date.getDate()}日 ${timeStr}`
  } else if (date >= threeMonthsAgo) {
    return `${date.getMonth() + 1}/${date.getDate()}`
  } else if (date >= oneYearAgo) {
    return `${date.getMonth() + 1}月${date.getDate()}日`
  } else {
    return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
  }
}